package com.example.automatic.abs_bank;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.RequiresApi;

import com.example.automatic.abs_bank.base.BaseAccessibilityService;
import com.example.automatic.receiver.SMSBroadcastReceiver;
import com.example.automatic.receiver.SMSContentObserver;
import com.example.automatic.single.GlobalHandler;
import com.example.automatic.utils.LogUtils;
import com.example.automatic.utils.ToastUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 建设银行-自动转账
 */
public class JSAccessibilityService extends BaseAccessibilityService implements GlobalHandler.HandlerMessageListener {

    /**
     * 转账主页面
     */
    //转账按钮
    private AccessibilityNodeInfo tvFunctionNodeInfo;

    /**
     * 转账页面控件
     */
    //下一步按钮是否可点击
    private boolean isClickableBtnRight1 = true;

    /**
     * “请输入验证码”对话框dialog控件
     */
    //验证码输入框
    private AccessibilityNodeInfo et_code;
    //确定按钮
    private AccessibilityNodeInfo btn_confirm;

    private Handler mHandler = new Handler();

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {

            socketManager.sendMessage("hello world!");

            mHandler.postDelayed(this, 30 * 1000);
        }
    };


    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();

        LogUtils.e("#建设银行无障碍服务已启动#");

        //设置handler短信监听
        GlobalHandler.getInstance().setHandlerMessageListener(this);

    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

//        AccessibilityNodeInfo accessibilityNodeInfo1 = getRootInActiveWindow();
//        if (accessibilityNodeInfo1 != null) {
//            LogUtils.e(event.getClassName() + "，" + accessibilityNodeInfo1.getClassName() + "，，，，" + event.toString());
//        }

        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            if (event.getClassName().equals("com.ccb.transfer.transfer_home.view.TransferHomeAct")) {
                AccessibilityNodeInfo nodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/tv_function", "转账");
                if (nodeInfo == null) {
                    return;
                }
                this.tvFunctionNodeInfo = nodeInfo;
                this.isClickableBtnRight1 = true;

            } else if (event.getClassName().equals("com.ccb.framework.security.login.internal.view.LoginActivity")) {

            } else if (event.getClassName().equals("com.ccb.transfer.smarttransfer.view.SmartTransferMainAct")) {
                //收款户名输入框
                AccessibilityNodeInfo etCashNameNodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/et_cash_name");
                //收款账号输入框
                AccessibilityNodeInfo etCollectionAccountNodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/et_collection_account");
                //转账金额输入框
                AccessibilityNodeInfo etTranAmountNodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/et_tran_amount");
                if (etCashNameNodeInfo == null || etCollectionAccountNodeInfo == null
                        || etTranAmountNodeInfo == null) {
                    //反馈给服务器
                    return;
                }
                if (mTransferAccount == null) {
                    //反馈给服务器
                    return;
                }
                //默认赋值
                changeInput(etCashNameNodeInfo, mTransferAccount.getName());
                changeInput(etCollectionAccountNodeInfo, mTransferAccount.getAccount());
                changeInput(etTranAmountNodeInfo, mTransferAccount.getMoney());
                //故意获取焦点弹出安全软键盘
                etCollectionAccountNodeInfo.performAction(AccessibilityNodeInfo.FOCUS_INPUT);
                //调用物理返回键，收起软键盘
                boolean isGlobalActionBack = performGlobalAction(GLOBAL_ACTION_BACK);
                if (!isGlobalActionBack) {
                    return;
                }

                while (isClickableBtnRight1) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    AccessibilityNodeInfo btnRight1NodeInfo =
                            getAccessibilityNodeInfo("com.chinamworld.main:id/btn_right1", "下一步");
                    if (btnRight1NodeInfo == null) {
                        isClickableBtnRight1 = true;
                    } else {
                        if (btnRight1NodeInfo.isClickable()) {
                            isClickableBtnRight1 = false;
                            btnRight1NodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        } else {
                            isClickableBtnRight1 = true;
                        }
                    }
                }

            } else if (event.getClassName().equals("com.ccb.framework.security.transecurityverify.TransSecurityVerifyDialogAct")) {
                AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
                if (accessibilityNodeInfo == null) {
                    return;
                }
                List<AccessibilityNodeInfo> etCodeAccountList = accessibilityNodeInfo
                        .findAccessibilityNodeInfosByViewId("com.chinamworld.main:id/et_code");
                for (AccessibilityNodeInfo nodeInfo : etCodeAccountList) {
                    et_code = nodeInfo;
                }
                List<AccessibilityNodeInfo> btnConfirmList = accessibilityNodeInfo
                        .findAccessibilityNodeInfosByViewId("com.chinamworld.main:id/btn_confirm");
                for (AccessibilityNodeInfo nodeInfo : btnConfirmList) {
                    btn_confirm = nodeInfo;
                }
            } else if (event.getClassName().equals("android.app.AlertDialog")) {
                AccessibilityNodeInfo nodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/dlg_right_tv");
                AccessibilityNodeInfo contentNodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/tv_dlg_content");
                if (nodeInfo == null) {
                    return;
                }
                if (nodeInfo.getText().equals("继续")) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                } else {

                    if (contentNodeInfo != null) {
                        //反馈给服务器
                        LogUtils.e(contentNodeInfo.getText().toString());
                    }
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    performGlobalAction(GLOBAL_ACTION_BACK);
                }
            } else if (event.getClassName().equals("com.ccb.framework.security.base.successpage.CcbSuccessPageAct")) {
                AccessibilityNodeInfo nodeInfo =
                        getAccessibilityNodeInfo("com.chinamworld.main:id/ccb_title_right_btn", "完成");
                if (nodeInfo == null) {
                    return;
                }
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    }

    @Override
    public void onInterrupt() {

    }

    @Override
    public void onMessage(String text) {
        super.onMessage(text);
        if (tvFunctionNodeInfo == null) {
            return;
        }
        LogUtils.e("开始转账------");
        mTransferAccount = new TransferAccount();
        mTransferAccount.setName("林荔敏");
        mTransferAccount.setAccount("6214 9217 0095 9659");
        mTransferAccount.setMoney("30");

        coordinateClick(tvFunctionNodeInfo);
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what != 95533 || msg.obj == null) {
            return;
        }
        String code = (String) msg.obj;
        if (et_code != null && btn_confirm != null) {
            changeInput(et_code, code);
            AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
            if (accessibilityNodeInfo == null) {
                return;
            }
            List<AccessibilityNodeInfo> btnConfirmList = accessibilityNodeInfo
                    .findAccessibilityNodeInfosByViewId("com.chinamworld.main:id/btn_confirm");
            for (AccessibilityNodeInfo nodeInfo : btnConfirmList) {
                btn_confirm = nodeInfo;
            }
            if (btn_confirm == null) {
                return;
            }
            if (btn_confirm.isClickable()) {
                btn_confirm.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            } else {
                handleMessage(msg);
            }

        } else {
            LogUtils.e("验证码对话框：输入框或提交按钮控件为null");
        }
    }


}
